package tool.soft

import java.io.File
import akka.stream.Materializer
import dao._
import implicits.Implicits._
import models.Tables
import models.Tables._
import org.joda.time.DateTime
import play.api.data.FormBinding
import play.api.libs.ws.WSClient
import play.api.mvc.{AnyContent, Request}
import play.twirl.api.Html
import shared.Pojo._
import tool.Pojo._
import tool.plot._
import tool.soft.AllSoft.SoftBT
import tool._

import scala.language.postfixOps
import play.api.i18n.Messages
import upickle.default._

/**
 * Created by yz on 15/9/2020
 */
object MetMicCorSoft extends MetMicCorSoftT with SoftBT {

 override def getFileInfos(workspaceDir: File, index: Int)(implicit matrixFileDataDao: MatrixFileDataDao, messages: Messages): List[FileInfoData] = {
    List(
      FileInfoData("Correlation_Heatmap.pdf", messages("correlationHeatmap")),
      FileInfoData("Correlation_coefficients.csv", messages("correlationCoefficients")),
      FileInfoData("Correlation_p_values.csv", messages("correlationPValues")),
      FileInfoData("Correlation_methods.csv", messages("correlationMethods")),
      FileInfoData("Network_Nodes_for_Cytoscape.csv", messages("networkNodesForCytoscape")),
      FileInfoData("Network_Edges_for_Cytoscape.csv", messages("networkEdgesForCytoscape")),
      FileInfoData("R_value_top_10_pairs.pdf", messages("rValueTopPairs")),

    )
  }

  override def resultDeal(workspaceDir: File, resultDir: File)(implicit ws: WSClient, materializer: Materializer): Unit = {
    val excludeFileNames = List("Inter_Correlation_Heatmap.pdf", "Inter_P_Matrix.csv", "Inter_r_Matrix.csv",
      "R value top 10 pairs.pdf")
    Tool.resultDeal(workspaceDir, resultDir, excludeFileNames)
  }

   override def produceConfigFile(workspaceDir: File,index:Int)(implicit request: Request[AnyContent], formBinding: FormBinding) = {
   data.lines().toTxtFile(Tool.getCalculateConfigTxtFile(workspaceDir))
     plot.CorHeatmapPlot.initConfigFile(workspaceDir, idStr = "")
  }

  override def getResultHtml(missionId: Int)(implicit request: Request[AnyContent],messages: Messages): Html = {
    views.html.user.mission.metMicCorResult(missionId)
  }

  def getArg(implicit request: Request[AnyContent], messages: Messages, formBinding: FormBinding): ujson.Value = {
    val hasCov = if (data.hasCov.isDefined) messages("yes") else messages("no")
    ujson.Obj(messages("importDataMatrixOfCovariates") -> hasCov, messages("dataNormalization") -> Tool.getTFStr(data.metaNor),
      messages("resampling") -> Tool.getTFStr(data.rarefaction),
      messages("coefficientCutoff") -> data.r, messages("pCutoff") -> data.alpha, messages("correlationCutoff") -> data.coe, messages("pValueCutoff") -> data.p)
  }

   override def getCommandData(workspaceDir: File, resultDir: File, index: Int):  List[CommandData] = {
    val solutionFile = new File(Tool.dataDir, "color_solution/color_solution_1.txt")
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    val command =
      s"""
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "gramm4R.R").unixPath}
         |cp Correlation_coefficients.csv r_Matrix.csv
         |cp Correlation_p_values.csv P_Matrix.csv
         |cp "R value top 10 pairs.pdf" R_value_top_10_pairs.pdf
           """.stripMargin
     val plotCommand = plot.CorHeatmapPlot.getCommand(workspaceDir, "")
     List(CommandData(workspaceDir, List(command,plotCommand)))
  }

  override def getHtml(missionName: String, missionId: Option[Int])(implicit request: Request[AnyContent],messages: Messages): Html = {
    views.html.user.soft.metMicCor(missionName, missionId)
  }

   override def getMission(implicit request: Request[AnyContent], matrixFileDataDao: MatrixFileDataDao, messages: Messages, formBinding: FormBinding): Tables.MissionRow = {
    val initInput = List(data.file, data.micFile)
    val input = if (data.hasCov.isDefined) initInput ::: List(data.covFile) else initInput
    val argJson = getArg
    MissionRow(id = 0, missionName = s"${data.missionName}", kind = nameStr, userId = userId,
      startTime = new DateTime(), state = "preparing", arg = argJson, input = input)
  }

  override def produceInputFile(workspaceDir: File)(implicit request: Request[AnyContent], dao: MyDao, formBinding: FormBinding): Any = {
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceRawMetaboliteFile(userId, data.file, rawDataFile)
    val micFile = new File(workspaceDir, "mic_data.txt")
    Tool.produceRawMetaboliteFile(userId, data.micFile, micFile)
    if (data.hasCov.isDefined) {
      val covFile = new File(workspaceDir, "cov_data.txt")
      Tool.produceRawMetaboliteFile(userId, data.micFile, covFile)
    }

  }

  override def data(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    FormTool.metMicCorForm.bindFromRequest().get
  }


}

